package com.xxx.blog.web.admin;

import com.xxx.blog.po.User;
import com.xxx.blog.service.CommentService;
import com.xxx.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    @Resource
    private CommentService commentService;
    @Resource
    private UserService userService;
    @GetMapping
    public String loginPage(){
        return "admin/login";
    }
    @PostMapping("/login")
    public String login(@PageableDefault(size = 5, sort = {"id"}, direction = Sort.Direction.DESC) Pageable pageable, @RequestParam String username, @RequestParam String password,
                        HttpSession session, RedirectAttributes attributes,
                        Model model){
        BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
        User user=userService.getUser(username);
        if (user!=null&&(encoder.matches(password,user.getPassword()))){
            user.setPassword(null);
            session.setAttribute("user",user);
            model.addAttribute("page", commentService.adminListComment(pageable));
            return "admin/index";
        }else {
            attributes.addFlashAttribute("message","用户名或者密码错误");
            return "redirect:/admin";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
